from typing import Tuple
import matplotlib.pyplot as plt
import numpy as np

from .fig_settings import fontdict
from .fig_settings import figdict
from .simulation import run
from .simulation import post_process


def txt_read(file: str) -> Tuple[:, 2]:
    """
    read txt file
    :param file: filename 'example.txt'
    :return:
    """
    data = np.loadtxt(file)
    return data


class ECHO2D:
    def __init__(self, filename):
        self.filename = filename
        self.data = txt_read(filename)

    def swap_x_and_y(self) -> Tuple[:, 2]:
        """将腔的x,y坐标互换"""
        temp = self.data[:, 0].copy()
        self.data[:, 0] = self.data[:, 1].copy()
        self.data[:, 1] = temp.copy()
        return self.data

    def axisymmetric_operation(self) -> Tuple[:, 2]:
        """将腔轴对称一下，返回对称后补全的腔 axisymmetric operation"""
        mirror = self.data[::-1, :].copy()
        mirror[:, 0] = -mirror[:, 0]
        cavity = np.concatenate((mirror, self.data), axis=0)
        return cavity

    def data2model(self, modelname: str = 'cavity.txt') -> None:
        """把数据转为建模文件"""
        start = self.data[:-1, :]
        end = self.data[1:, :]
        other = np.zeros([len(start), 6])  # 目前已知最后一列为电导率 [?,?,?,?,?,电导率]
        other[:, 5] = 54e6  # 设置电导率
        other[:, 4] = 1  # 案例上是这样设置的
        data = np.concatenate((start, end, other), axis=1)

        data1 = [1]  # 文件里面说的材料数目
        data2 = [len(data), 1, 1, 0]  # 文件里面的一串很长的描述

        with open(modelname, 'w', encoding='utf-8') as file:
            file.write('% Number of materials' + '\n')
            data1 = ' '.join(f'{num}' for num in data1)
            file.write(''.join(map(str, data1)) + '\n')
            file.write(
                '% Number of elements in metal with conductive walls, permeability, permitivity, conductivity' + '\n')
            data2 = ' '.join(f'{num}' for num in data2)
            file.write(''.join(map(str, data2)) + '\n')
            file.write(
                '% Segments of lines and elipses with conductivity' + '\n')
            for row in data:
                row = ''.join(f'{num:<20.8e}' for num in row)
                file.write(''.join(map(str, row)) + '\n')

    def cavity_plot(self, figname: str = 'cavity') -> None:  # 设置标记大小为 4，使数据点标记清晰可辨
        """plot cavity shape"""
        plt.rcParams.update(figdict)
        plt.figure()
        plt.plot(self.data[:, 0], self.data[:, 1], )
        plt.xlabel("Z(mm)", fontdict=fontdict)
        plt.ylabel("R(mm)", fontdict=fontdict)
        plt.tight_layout()
        # plt.show(block=True)
        plt.savefig(figname)
        plt.close()

    def run(self):
        """自动运行计算"""
        raise '还没有完善此部分工作，敬请期待...'

    def postprocess(self):
        """自动运行计算"""
        raise '还没有完善此部分工作，敬请期待...'